package com.enlorenz.support.jackson;

import java.util.Map;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonUtils {
	public static final String EMPTY_JSON_STRING="{}";
	
	/**
	 * 写出字符串
	 * @param object 对象
	 * @return json字符串
	 */
	public static String writeString(Object object){
		if(null == object){
			return EMPTY_JSON_STRING;
		}
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writeValueAsString(object);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 读取map对象
	 * @param value 字符串
	 * @return map对象
	 */
	public static Map readMap(String value){
		return readValue(value, Map.class);
	}
	
	/**
	 * 将json字符串读取为对象
	 * @param <T>
	 * @param value 字符串
	 * @param claxx 类对象
	 * @return 对象
	 */
	public static <T> T readValue(String value,Class<T> claxx){
		ObjectMapper mapper = new ObjectMapper();  
		mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
		try {
			return mapper.readValue(value,claxx);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
